package edu.uc.ui;

import edu.uc.service.IUserService;
import edu.uc.service.UserServiceStub;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class IntroScreen extends CeasBaseScreen{
	public static final String USER_NAME_KEY = "USER_NAME_KEY";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro_screen);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.intro_screen, menu);
		return true;
	}
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.btnNewUser:
			Intent intent = new Intent(IntroScreen.this,
					CreateNewUserScreen.class);
			startActivity(intent);
			break;
		case R.id.btnLogin:
			login();
			break;
		default:
			break;
		}
	}
	private void login() {
		final String user = ((EditText) findViewById(R.id.txtUser)).getText()
				.toString();
		final String pass = ((EditText) findViewById(R.id.txtPwd)).getText()
				.toString();
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage("Login...");
		dialog.show();
		new Thread(new Runnable() {

			@Override
			public void run() {
				if (user == null || user.equals("") || pass == null || pass.equals("")){
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(IntroScreen.this,
									"User and Password are required", 3).show();
						};
					});
				}else{
					IUserService service = new UserServiceStub();
					
					boolean isOk = false;
					try {
						isOk = service.logon(user, pass);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	
					if (isOk) {
						SharedPreferences.Editor editor = getPreferences(
								MODE_PRIVATE).edit();
						Intent intent = new Intent(IntroScreen.this,
								LoggedInScreen.class);
						editor.putString(USER_NAME_KEY, user);
						intent.putExtra(USER_NAME_KEY, user);
						editor.commit();
						startActivity(intent);
						IntroScreen.this.finish();
					} else {
						runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(IntroScreen.this,
										"Incorrect account", 3).show();
							};
						});
	
					}
				}
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
					}
				});
			}
		}).start();
	}

}
